package com.ywwxhz.app.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;

import com.ywwxhz.Util.PreferencesKit;
import com.ywwxhz.Util.ToolKit;
import com.ywwxhz.Util.UIKit;
import com.ywwxhz.adapter.IgnoreListAdapter;
import com.ywwxhz.model.AppInfo;
import com.ywwxhz.model.Category;
import com.ywwxhz.taskmgr.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import za.co.immedia.pinnedheaderlistview.PinnedHeaderListView;

public class IgnoreListFragment extends Fragment implements IFragmentShouldExit {
    public static final int TASK_IGNORE = 1;
    public static final int BATTERY_IGNORE = 2;
    public static final String KEY = "mode";
    ProgressDialog myDialog;
    String fixignore = ToolKit.getFixIgnoreList();
    private PinnedHeaderListView mListview = null;
    private List<Category> categories = null;
    private Handler myhandle;
    private IgnoreListAdapter browseAppAdapter;
    Runnable updateUI = new Runnable() {
        public void run() {
            browseAppAdapter = new IgnoreListAdapter(getActivity(),
                    categories);
            mListview.setAdapter(browseAppAdapter);
            if (myDialog.isShowing())
                myDialog.cancel();
        }
    };
    Runnable getAppinfo = new Runnable() {
        public void run() {
            queryAppInfo(); // 查询所有应用程序信息
            myhandle.post(updateUI);
        }
    };
    private boolean ischanged = false;
    private boolean canexit = false;
    private int mode = TASK_IGNORE;
    private PackageManager pm;
    private Category ignored;
    private Category normal;
    private Category fixed;
    private int left, right, top, bottom;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mode = bundle.getInt(KEY, TASK_IGNORE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        activity.getActionBar().setSubtitle(R.string.pref_ignorelist_title);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ignore_list, container, false);
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pm = getActivity().getPackageManager(); // 获得PackageManager对象
        myDialog = ProgressDialog.show(getActivity(), null, getString(R.string.Loading),
                true, false);
        myhandle = new Handler();
        ignored = new Category("Has ignored");
        normal = new Category("Normal");
        fixed = new Category("Fixed ignored");
        mListview = (PinnedHeaderListView) view.findViewById(R.id.listviewApp);
        mListview.setPinHeaders(false);
        left = mListview.getPaddingLeft();
        right = mListview.getPaddingRight();
        top = mListview.getPaddingTop();
        bottom = mListview.getPaddingBottom();
        UIKit.fixTranslucentStatusPadding(getActivity(), mListview, UIKit.PaddingMode.SET_ALL, left, top, right, bottom);
        categories = new ArrayList<Category>();
        mListview.setOnItemClickListener(new PinnedHeaderListView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                                    int section, int position, long id) {
                ischanged = true;
                CheckBox checkBox = (CheckBox) view
                        .findViewById(R.id.checkBox1);
                checkBox.setChecked(!checkBox.isChecked());
                ((AppInfo) browseAppAdapter.getItem(section, position))
                        .setCheched(checkBox.isChecked());

            }

            @Override
            public void onSectionClick(AdapterView<?> adapterView, View view,
                                       int section, long id) {
            }

        });
        new Thread(getAppinfo).start();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_ignorelist, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.save:
                StringBuffer sb = new StringBuffer();
                for (AppInfo appInfo : ignored.getApps()) {
                    if (appInfo.isCheched()) {
                        sb.append(",");
                        sb.append(appInfo.getPkgName());
                    }
                }
                for (AppInfo appInfo : normal.getApps()) {
                    if (appInfo.isCheched()) {
                        sb.append(",");
                        sb.append(appInfo.getPkgName());
                    }
                }
                if (mode == TASK_IGNORE) {
                    PreferencesKit.writePref(getActivity(), getString(R.string.pref_ignorelist_key), sb.toString());
                } else {
                    PreferencesKit.writePref(getActivity(), "batterylist", sb.toString());
                }
                ToolKit.MakeToast(getActivity(), "保存完成");
                ischanged = false;
                myDialog.show();
                categories.clear();
                new Thread(getAppinfo).start();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void queryAppInfo() {
        String ignorelist = ToolKit.getIgnoreList(getActivity());

        List<ApplicationInfo> appInfos = pm
                .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(appInfos, new Comparator<ApplicationInfo>() {

            @Override
            public int compare(ApplicationInfo lhs, ApplicationInfo rhs) {
                return lhs.loadLabel(pm).toString()
                        .compareTo(rhs.loadLabel(pm).toString());
            }
        });
        if (categories != null) {
            categories.clear();
            ignored.clear();
            normal.clear();
            fixed.clear();
            for (ApplicationInfo appInfo : appInfos) {
                // 创建一个AppInfo对象，并赋值
                AppInfo app = new AppInfo();
                app.setAppLabel(appInfo.loadLabel(pm).toString());
                app.setPkgName(appInfo.packageName);
                app.setAppIcon(appInfo.loadIcon(pm));
                if (fixignore.contains(appInfo.packageName)) {
                    fixed.add(app);
                    app.setClickable(false);
                } else if (ignorelist.contains(appInfo.packageName)) {
                    ignored.add(app);
                    app.setCheched(true);
                } else {
                    normal.add(app);
                }
            }
            categories.add(ignored);
            categories.add(normal);
            categories.add(fixed);
        }
    }

    @Override
    public boolean getShouldExit() {
        if (ischanged && !canexit) {
            ToolKit.MakeToast(getActivity(), "配置更改，还没有保存。。再点一次强制退出");
            canexit = true;
            new Thread() {
                public void run() {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    canexit = false;
                }
            }.start();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        UIKit.fixTranslucentStatusPadding(getActivity(), mListview, UIKit.PaddingMode.SET_ALL, left, top, right, bottom);
    }
}
